package com.asset.salesforce.utils;

import com.asset.salesforce.domain.User;
import com.asset.salesforce.service.UserShiroService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author Hisham Mounir
 * this class is used to extend HandlerInterceptorAdapter to add the logged in user to the session 
 *
 */
@Component
public class CurrentUserInterceptor extends HandlerInterceptorAdapter {
	
	/** The user shiro service. */
	@Autowired
    private UserShiroService userShiroService;

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        // Add the current user into the request
        User currentUser = userShiroService.getCurrentUser();
        if( currentUser != null ) {
            httpServletRequest.setAttribute( "currentUser", currentUser );
        }
    }
}
